use std::io;

use tokio::{
  io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
  net::TcpStream,
  sync::mpsc,
};

const LOCAL_SERVER: &str = "127.0.0.1:8888";

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
  let mut client = TcpStream::connect(LOCAL_SERVER).await?;

  // 从io::stdin
  let (tx, mut rx) = mpsc::channel::<String>(3);
  tokio::spawn(async move {
    let (r, mut w) = client.split();
    let mut r = BufReader::new(r);
    let mut line = String::new();
    loop {
      tokio::select! {
       result = r.read_line(&mut line) => {

        if result.unwrap() == 0 {
         break;
        }

        println!("recv: {}", line);
        line.clear();
       }

       result = rx.recv() => {
        let msg = result.unwrap();
        println!("发送的数据: {}", msg);
        w.write_all(msg.as_bytes()).await.unwrap();
       }
      }
    }
  });

  println!("请输入:");

  loop {
    let mut buff = String::new();

    io::stdin()
      .read_line(&mut buff)
      .expect("从 stdin 读取数据失败");

    tx.send(buff.clone()).await.unwrap();
    buff.clear();
  }
}
